//
//  RefreshProgressView.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/28.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "RefreshProgressView.h"

@interface RefreshProgressView ()
/** 旋转菊花 */
@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;
@end

@implementation RefreshProgressView

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        
        UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhite)];
        indicatorView.center = CGPointMake(self.width * 0.5, self.height * 0.5);
        [self addSubview:indicatorView];
        
        _indicatorView = indicatorView;
    }
    return _indicatorView;
}

- (void)setProgress:(CGFloat)progress{
    
    progress = progress < 0.05 ? 0 : progress;
    
    if (_progress == progress && progress <= 0) {
        return;
    }
    
    _progress = progress;
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    if (self.progress <= 0) {
        return;
    }
    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
    
    //以下数字都是慢慢微调出来的~~
    CGFloat radius = rect.size.width > rect.size.height ? rect.size.height * 0.4 : rect.size.width * 0.4;
    CGFloat startA = M_PI_2;
    CGFloat endA = startA + self.progress * M_PI * 2;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    
    path.lineWidth = 1;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle= kCGLineJoinRound;
    [JKColor(217, 217, 217) set];
    [path stroke];
}

/** 菊花开始旋转 */
- (void)beginAnimating{
    self.progress = 0;
    
    [self.indicatorView startAnimating];
}

/** 菊花停止旋转 */
- (void)stopAnimating{
    
    [self.indicatorView stopAnimating];
    [self removeFromSuperview];
}
@end
